package com.masasdani.paypal.controller;

import com.alibaba.fastjson2.JSON;
import com.paypal.api.payments.Event;
import com.paypal.api.payments.Sale;
import com.paypal.base.rest.APIContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@WebServlet("/paypal/webhook")
public class PayPalWebhookController extends HttpServlet {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private APIContext apiContext;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StringBuilder sb = new StringBuilder();
        Map<String, String> headers = new HashMap<>();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }

        String requestBody = sb.toString();
        logger.info("Received PayPal Webhook: " + requestBody);
        try {
            Event event = JSON.parseObject(requestBody, Event.class);
            handleEvent(event);
            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    private void handleEvent(Event event) {
        String eventType = event.getEventType();
        logger.info("Handling event type: " + eventType);

        switch (eventType) {
            case "BILLING.SUBSCRIPTION.ACTIVATED":
                handleSubscriptionActivated(event);
                break;
            case "BILLING.SUBSCRIPTION.CANCELLED":
                handleSubscriptionCancelled(event);
                break;
            case "BILLING.SUBSCRIPTION.RENEWED":
                handleSubscriptionRenewed(event);
                break;
            case "PAYMENT.SALE.COMPLETED":
                handleSaleCompleted(event);
                break;
            case "PAYMENT.SALE.REFUNDED":
                handleSaleRefunded(event);
                break;
            // 处理其他事件类型
            default:
                logger.info("Unhandled event type: " + eventType);
        }
    }

    private void handleSubscriptionActivated(Event event) {
        // 处理订阅激活事件
        logger.info("Subscription activated: " + event.toJSON());
    }

    private void handleSubscriptionCancelled(Event event) {
        // 处理订阅取消事件
        logger.info("Subscription cancelled: " + event.toJSON());
    }

    private void handleSubscriptionRenewed(Event event) {
        // 处理订阅续费事件
        logger.info("Subscription renewed: " + event.toJSON());
    }

    private void handleSaleCompleted(Event event) {
        // 支付完成时间
        Sale sale = (Sale) event.getResource();
        String saleId = sale.getId();
        System.out.println("Sale ID: " + saleId);
        //设置支付完成的Id
        logger.info("handle sale completed: " + event.toJSON());
    }

    private void handleSaleRefunded(Event event) {
        // 处理退款事件
        logger.info("handle sale refunded: " + event.toJSON());
    }
}
